library(tidyverse)
library(networkD3)
library(htmlwidgets)Top 10 Countries in Olympics: Sankey Diagram
Data Visualization
R
Objective:
The goal is to create an interactive, easy-to-understand visualization of the medal counts for the top 10 countries in the Olympics, highlighting both the total number of medals and the breakdown by type (Gold, Silver, Bronze). Users can explore how medals flow from types (Gold, Silver, Bronze) to the countries that earned them.
Code:
# Input data
medal_data <- data.frame(
Nation = c("United States", "Russia", "Germany", "China", "Great Britain",
"France", "Italy", "Sweden", "Norway", "Japan"),
Gold = c(1219, 748, 617, 325, 310, 280, 271, 216, 213, 206),
Silver = c(1000, 634, 625, 258, 344, 320, 244, 232, 187, 191),
Bronze = c(876, 627, 617, 221, 360, 354, 284, 242, 176, 221)
)
# Pivoted the data to long format for Sankey diagram
medal_long <- medal_data |>
pivot_longer(cols = c(Gold, Silver, Bronze),
names_to = "Medal",
values_to = "Count")
medals <- unique(medal_long$Medal)
countries <- medal_data$Nation
nodes <- data.frame(
name = c(medals, countries)
)
links <- medal_long |>
mutate(
source = match(Medal, nodes$name) - 1,
target = match(Nation, nodes$name) - 1,
value = Count
) |>
select(source, target, value)
# Create the Sankey diagram
sankey_chart <- sankeyNetwork(
Links = links,
Nodes = nodes,
Source = "source",
Target = "target",
Value = "value",
NodeID = "name",
sinksRight = FALSE,
nodeWidth = 30,
nodePadding = 10,
height = 600,
width = 800,
fontSize = 14,
margin = list(left = 0, right = 0)
)Output:
This visualizes the Olympic medal distribution for the top 10 countries using a Sankey diagram. The diagram shows how many Gold, Silver, and Bronze medals each country won. On the left side, you’ll see the medal types, and on the right, the countries.